
<template>
  <div>
    <el-form :model="dataForm" :rules="rules" ref="dataForm" label-width="100px">
      <el-form-item prop="CID" label="选择小区">
        <el-select
          @change="change_CID"
          v-model="dataForm.CID"
          filterable
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in getCommunity"
            :key="item.CID"
            :label="item.name"
            :value="item.CID"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="BID" label="选择楼栋">
        <el-select @change="pickdong" v-model="dataForm.BID" filterable placeholder="请选择" clearable>
          <el-option v-for="item in maxdong" :key="item.BID" :label="item.name" :value="item.BID"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="UID" label="选择单元">
        <el-select
          @change="pickdanyuan"
          v-model="dataForm.UID"
          filterable
          placeholder="请选择"
          clearable
        >
          <el-option
            v-for="item in maxdanyuan"
            :key="item.UID"
            :label="item.name"
            :value="item.UID"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="FID" label="选择楼层">
        <el-select @change="pickceng" v-model="dataForm.FID" filterable placeholder="请选择" clearable>
          <el-option v-for="item in maxceng" :key="item.FID" :label="item.name" :value="item.FID"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="HID" label="选择房屋">
        <el-select v-model="dataForm.HID" filterable placeholder="请选择" clearable>
          <el-option v-for="item in maxhao" :key="item.HID" :label="item.name" :value="item.HID"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备名" prop="name">
        <el-input placeholder="请填写" v-model="dataForm.name" clearable></el-input>
      </el-form-item>
      <el-form-item label="设备id" prop="imei">
        <el-input placeholder="请填写" v-model="dataForm.imei" clearable></el-input>
      </el-form-item>
      <el-form-item label="经度" prop="lon">
        <el-input v-model="dataForm.lon" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="纬度" prop="lat">
        <el-input v-model="dataForm.lat" auto-complete="off"></el-input>
      </el-form-item>
      <div id="map_box_edit" style="width: 100%; height: 500px"></div>
      <p>当前鼠标经纬度：{{ move }}</p>
    </el-form>
    <div slot="footer" class="dialog-footer cen">
      <el-button @click.native="closedialog">取消</el-button>
      <el-button type="primary" @click.native="submitForm">确认</el-button>
    </div>
  </div>
</template>
<script>
export default {
  // 父级传递进来的数据的定义 好比重新定义变量来接收
  props: {
    data: {
      type: Object,
    },
    communities: {
      type: Array,
    },
    editData: {
      type: Object,
    },
  },
  // 本文件内部的变量 作用于在本文件内
  data() {
    return {
      dataForm: {
        type:1,
        CID: "",
        BID: "",
        FID: "",
        UID: "",
        HID: "",
        name: "",
        imei: "",
        lon: "",
        lat: "",
      },
      move: "",
      getCommunity: [],
      dictList: [],
      maxdong: [],
      maxdanyuan: [],
      maxceng: [],
      maxhao: [],
      getCommunity: [],
      dictList: {},
      rules: {
        CID: [{ required: true, message: "请选择小区", trigger: "change" }],
        BID: [{ required: true, message: "请选择楼栋", trigger: "change" }],
        UID: [{ required: true, message: "请选择单元", trigger: "change" }],
        FID: [{ required: true, message: "请选择楼层", trigger: "change" }],
        HID: [{ required: true, message: "请选择房号", trigger: "change" }],
        imei: [
          { required: true, message: "请填写设备id", trigger: "blur" },
        ],
        name: [{ required: true, message: "请填写设备名", trigger: "blur" }],
        lon: [{ required: true, message: "必填项", trigger: "blur" }],
        lat: [{ required: true, message: "必填项", trigger: "blur" }],
      },
    };
  },
  // 监听事件 监听写在这里的变量值的变化
  watch: {
    editData: {
      handler(val) {
        if (val) {
          this.dataForm = Object.assign(this.dataForm, val);
        }
      },
      deep: true,
    },
  },
  //本文件内所有的函数方法
  methods: {
    getmap() {
      // 初始化地图
      // 定义局部变量 userinfo 赋值为 storage里面的 userinfo
      var userInfo = JSON.parse(sessionStorage.getItem("userInfo")); // 定义中心点变量 center 赋值为空数组
      var center = []; // 增加if判断 括号里面判断条件为 userinfo里面的 经度存在 并且 纬度也存在
      if (userInfo.lon && userInfo.lat) {
        center = [userInfo.lon, userInfo.lat];
      } else {
        center = [104.06667, 30.66667];
      }
      var map = new AMap.Map("map_box_edit", {
        zoom: 16,
        resizeEnable: true,
        resizeEnable: true,
        center: center,
      });
      map.plugin(["AMap.ToolBar"], function () {
        // 组件初始化成功 new 工具条组件对象 这里根据官方规定 定义 AMap.ToolBar 的组件
        var tool = new AMap.ToolBar();
        // 地图中添加工具条  map 是前面定义的地图对象 通过 组件内部的 addControl 方法 （官方定义） 添加tool这个变量 即工具条
        map.addControl(tool);
      });

      let clickFunc = (e) => {
        // 如果已存在 移除已创建的 marker
        if (this.marker) map.remove(this.marker);
        this.dataForm.lon = e.lnglat.getLng();
        this.dataForm.lat = e.lnglat.getLat();
        // 创建一个 Marker 实例：
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat()), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          // 设置是否可以拖拽
          draggable: true,
          cursor: "move",
          // 设置拖拽效果
          raiseOnDrag: true,
        });
        // 拖动结束事件
        this.marker.on("dragend", (e) => {
          this.dataForm.lon = e.lnglat.getLng();
          this.dataForm.lat = e.lnglat.getLat();
        });
        // 将创建的点标记添加到已有的地图实例：
        map.add(this.marker);
      };
      // 编辑第一次进入 回显图标到地图上
      if (this.dataForm.lon && this.dataForm.lat) {
        map.setCenter(new AMap.LngLat(this.dataForm.lon, this.dataForm.lat));
        this.marker = new AMap.Marker({
          position: new AMap.LngLat(this.dataForm.lon, this.dataForm.lat), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
          // 设置是否可以拖拽
          draggable: true,
          cursor: "move",
          // 设置拖拽效果
          raiseOnDrag: true,
        });
        // 拖动结束事件
        this.marker.on("dragend", (e) => {
          this.dataForm.lon = e.lnglat.getLng();
          this.dataForm.lat = e.lnglat.getLat();
        });
        map.add(this.marker);
      }
      let moveFunc = (e) => {
        this.move =
          "经度：" + e.lnglat.getLng() + "," + "纬度：" + e.lnglat.getLat();
      };
      map.on("click", clickFunc);
      map.on("mousemove", moveFunc);
    },
    // 关闭
    closedialog() {
      this.$emit("handleSave");
    },

    // 表单提交
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.editLoading = true;
          let params = {
              type:1,
              IMEI:this.dataForm.imei,
              CID:this.dataForm.CID,
              HID:this.dataForm.HID,
              name:this.dataForm.name,
              lon:this.dataForm.lon,
              lat:this.dataForm.lat
            }
          this.$confirm("确认提交吗？", "提示", {}).then(() => {
        
            this.$api.build.gsm_alarm_bindOrunbind(params).then((res) => {
              this.editLoading = false;
              if (res.code == 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                });
                this.$emit("handleSave");
              } else {
                this.$message({
                  message: "操作失败, " + res.msg,
                  type: "error",
                });
              }
            });
          });
        }
      });
    },

    // 根据选择的小区cid获取楼栋
    change_CID(e, isClear) {
      let that = this;
      if (!e) {
        that.maxdong = [];
        that.maxdanyuan = [];
        that.maxceng = [];
        that.maxhao = [];
        that.dataForm.BID = "";
        that.dataForm.UID = "";
        that.dataForm.FID = "";
        that.dataForm.HID = "";
        return;
      }
      this.$http
        .post(`${that.global.baseUrl}/admin/service/sys_building_list_weChat`, {
          page: 1,
          limit: 100,
          type: 1,
          sort: { name: -1 },
          where: { CID: that.dataForm.CID },
        })
        .then((res) => {
          that.maxdong = res.data;
          if (!isClear) {
            that.maxdanyuan = [];
            that.maxceng = [];
            that.maxhao = [];
            that.dataForm.BID = "";
            that.dataForm.UID = "";
            that.dataForm.FID = "";
            that.dataForm.HID = "";
          }
        });
    },
    //选择完楼栋
    pickdong(e, isClear) {
      let that = this;
      this.$http
        .post(`${that.global.baseUrl}/admin/service/sys_building_list_weChat`, {
          page: 1,
          limit: 100,
          type: 2,
          sort: { "name": -1 },
          where: { BID: that.dataForm.BID },
        })
        .then((res) => {
          that.maxdanyuan = res.data;
          if (!isClear) {
            that.maxceng = [];
            that.maxhao = [];
            that.dataForm.UID = "";
            that.dataForm.FID = "";
            that.dataForm.HID = "";
          }
        });
    },
    pickdanyuan(e, isClear) {
      let that = this;
      this.$http
        .post(`${that.global.baseUrl}/admin/service/sys_building_list_weChat`, {
          page: 1,
          limit: 100,
          type: 3,
          sort: { "name": -1 },
          where: { UID: that.dataForm.UID },
        })
        .then((res) => {
          that.maxceng = res.data;
          if (!isClear) {
            that.maxhao = [];
            that.dataForm.FID = "";
            that.dataForm.HID = "";
            that.FID = "";
            that.HID = "";
          }
        });
    },
    pickceng(e, isClear) {
      let that = this;
      this.$http
        .post(`${that.global.baseUrl}/admin/service/sys_building_list_weChat`, {
          page: 1,
          limit: 100,
          type: 4,
          sort: { "name": -1 },
          where: { CID: "", FID: that.dataForm.FID },
        })
        .then((res) => {
          that.maxhao = res.data;
          if (!isClear) {
            that.dataForm.HID = "";
            that.HID = "";
          }
        });
    },
  },
  // dom加载完成触发事件
  mounted() {
    // 某个外部参数
    this.getCommunity = this.communities;
    // 字典列表
    this.dictList = JSON.parse(sessionStorage.getItem("dictData"));
    // 外部点击编辑后传入的数据
    // house字段 楼栋数据
    let house = this.editData.house[0];
    // 重新赋值
    this.dataForm = Object.assign(this.dataForm, house);
    this.dataForm = Object.assign(this.dataForm, this.editData);

    // 由于多个下拉菜单是联动的 选择小区会调用接口查看楼栋 所以回显的时候需要一级一级获取
    this.change_CID("1", true); // 先根据小区回显楼栋
    this.pickdong("1", true); // 根据楼栋回显单元
    this.pickceng("1", true); // 根据楼层回显房屋
    this.pickdanyuan("1", true); // 根据单元回显楼层
    this.getmap();
  },
};
</script>
<style lang="scss" scoped>
.cen {
  text-align: center;
}
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}
.mr20 {
  margin-right: 20px;
}
.el-select {
  display: block;
  position: relative;
}
</style>
